package com.github.thinwonton.springboot.showcase.jta.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * jta-orders库数据源配置
 *
 * @author hugo
 * @date 2018/8/21
 */
@Configuration
@MapperScan(
        basePackages = "com.github.thinwonton.springboot.showcase.jta.orders.dao",
        sqlSessionFactoryRef = "jtaOrdersSqlSessionFactory"
)
@EnableConfigurationProperties({MybatisProperties.class})
public class JTAOrdersDataSourceConfig {

    private static final String MAPPER_LOCATION = "classpath:mapping/jta_orders/*.xml";

    private static final String TYPE_ALIASES_PACKAGE = "com.github.thinwonton.springboot.showcase.jta.orders.domain";

    private static final String CONFIG_PROPERTIES_PREFIX = "spring.datasource.jta-orders";

    private final MybatisProperties mybatisProperties;

    @Autowired
    public JTAOrdersDataSourceConfig(MybatisProperties mybatisProperties) {
        this.mybatisProperties = mybatisProperties;
    }

    @ConfigurationProperties(prefix = CONFIG_PROPERTIES_PREFIX)
    @Bean
    public DruidXADataSource jtaOrdersDruidXADataSource() {
        return new DruidXADataSource();
    }

    @Bean
    @Primary
    public DataSource jtaOrdersDataSource() {
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(jtaOrdersDruidXADataSource());

        return atomikosDataSourceBean;
    }

    @Bean(name = "jtaOrdersSqlSessionFactory")
    @Primary
    public SqlSessionFactory jtaOrdersSqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(jtaOrdersDataSource());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MAPPER_LOCATION));
        sessionFactory.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        sessionFactory.setConfiguration(mybatisProperties.getConfiguration());
        return sessionFactory.getObject();
    }
}
